/*
 * @Descripttion: 自定义合成事件(处理基本的合成事件)
 * @Author: lukasavage
 * @Date: 2021-12-16 20:50:08
 * @LastEditors: lukasavage
 * @LastEditTime: 2021-12-27 23:24:56
 */

import { updateQueue } from './component2';

/**
 * 给DOM添加合成事件
 * 为什么react要人工合成事件？
 * 1.希望在用户调用handler函数前后做一些事情
 * 2.处理函数的浏览器兼容性，提供兼容所有的浏览器的同意API，屏蔽浏览器的差异
 * @param {*} dom 真实DOM
 * @param {*} eventType 事件类型,例如onclick
 * @param {*} handler 事件回调
 */
function addEvent(dom, eventType, handler) {
	let store = dom._store || (dom._store = {});
	store[eventType] = handler;
	if (!document[eventType]) document[eventType] = dispatchEvent;
}

function dispatchEvent(nativeEvent) {
	updateQueue.isBatchingUpdate = true;
	// type = click tartget 事件源 如果点击是button的话那么就是button
	let { type, target } = nativeEvent;
	const eventType = `on${type}`;
	const syntheticEvent = createSyntheticEvent(nativeEvent);

    const { _store } = target;
	let handler = _store && _store[eventType];
	if (handler) handler(syntheticEvent);

	updateQueue.batchUpdate();
}

// 该函数相当于复制了一遍原本的event
function createSyntheticEvent(nativeEvent) {
	let syntheticEvent = {};
	for (const key in nativeEvent) {
		let value = nativeEvent[key];
		if (typeof value === 'function') value = value.bind(nativeEvent);
		syntheticEvent[key] = value;
	}
	syntheticEvent.nativeEvent = nativeEvent;
	return syntheticEvent;
}

export { addEvent };
